package cn.itcast.bos.web.action;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.constant.Constants;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.service.FixedAreaService;
import cn.itcast.bos.web.action.common.BaseAction;
import cn.itcast.crm.domain.Customer;

@ParentPackage(value = "json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class FixedAreaAction extends BaseAction<FixedArea> {

	private static final long serialVersionUID = 1L;

	@Autowired
	private FixedAreaService fixedAreaService;

	@Action(value = "fixedArea_save", results = {
			@Result(name = "success", type = "redirect", location = "./pages/base/fixed_area.html") })
	public String save() {
		fixedAreaService.save(model);
		return SUCCESS;
	}

	// 条件分页查询
	@Action(value = "fixedArea_pageQueryCondition", results = { @Result(name = "success", type = "json") })
	public String pageQueryCondition() {
		Pageable pageable = new PageRequest(page - 1, rows);
		Specification<FixedArea> specification = new Specification<FixedArea>() {

			Predicate predicate = null;
			List<Predicate> list = new ArrayList<Predicate>();

			@Override
			public Predicate toPredicate(Root<FixedArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				if (StringUtils.isNotBlank(model.getId())) {
					Predicate p = cb.equal(root.get("id").as(String.class), model.getId());
					list.add(p);
				}
				if (StringUtils.isNotBlank(model.getCompany())) {
					Predicate p = cb.like(root.get("company").as(String.class), "%" + model.getCompany() + "%");
					list.add(p);
				}

				if (list != null && list.size() > 0) {
					Predicate[] pArr = new Predicate[list.size()];
					predicate = cb.and(list.toArray(pArr));
				}

				return predicate;
			}
		};
		Page<FixedArea> pageDate = fixedAreaService.pageQueryCondition(specification, pageable);
		pushPageDataToValueStack(pageDate);
		return SUCCESS;
	}

	// webservice查询crm_management系统的数据
	@Action(value = "fixedArea_noassociationSelect", results = { @Result(name = "success", type = "json") })
	public String noassociationSelect() {
		Collection<? extends Customer> collection = WebClient
				.create(Constants.CRM_MANAGEMENT_URL + "/services/customerService").accept(MediaType.APPLICATION_JSON)
				.path("/findNoAssociationCustomers").getCollection(Customer.class);
		ServletActionContext.getContext().getValueStack().push(collection);
		return SUCCESS;
	}

	@Action(value = "fixedArea_associationSelect", results = { @Result(name = "success", type = "json") })
	public String associationSelect() {
		Collection<? extends Customer> collection = WebClient
				.create(Constants.CRM_MANAGEMENT_URL + "/services/customerService").accept(MediaType.APPLICATION_JSON)
				.path("/findHasAssociationFixedAreaCustomers/" + model.getId()).getCollection(Customer.class);
		ServletActionContext.getContext().getValueStack().push(collection);
		return SUCCESS;
	}

	// 关联客户
	// 属性驱动获取客户的id数组
	private String[] customerIds;
	public void setCustomerIds(String[] customerIds) {
		this.customerIds = customerIds;
	}

	@Action(value = "fixedArea_associationCustomersToFixedArea", results = {
			@Result(name = "success", type = "redirect", location = "./pages/base/fixed_area.html") })
	public String associationCustomersToFixedArea() {
		// 将客户id数组装换成中间用逗号隔开的字符串
		String customerIdStr = StringUtils.join(customerIds, ",");
		//webservice调用crm系统的方法
		WebClient.create(Constants.CRM_MANAGEMENT_URL + "/services/customerService/associationCustomersToFixedArea?customerIdStr="
				+customerIdStr+ "&fixedAreaId="+model.getId()).put(null);
		return SUCCESS;
	}

	// 属性驱动获取页面传递过来的id字符串
	private String ids;
	public void setIds(String ids) {
		this.ids = ids;
	}

	@Action(value = "fixedArea_delBatch", results = {
			@Result(name = "success", type = "redirect", location = "./pages/base/fixed_area.html") })
	public String delBatch() {
		String[] idArr = ids.split(",");
		fixedAreaService.deleteFixedArea(idArr);
		return SUCCESS;
	}
	
	//关联快递员
	//属性驱动获取快递员id和收派时间id
	private String courierId;
	private String takeTimeId;
	public void setCourierId(String courierId) {
		this.courierId = courierId;
	}
	public void setTakeTimeId(String takeTimeId) {
		this.takeTimeId = takeTimeId;
	}

	@Action(value="fixedArea_associationCourierToFixedArea",results={@Result(name="success",type="redirect",location="./pages/base/fixed_area.html")})
	public String associationCourierToFixedArea() {
		/**
		 * 该方法涉及到三个对象，快递员，定区，收派时间
		 */
		fixedAreaService.associationCourierToFixedArea(model.getId(),courierId,takeTimeId);
		return SUCCESS;
	}
	
	//根据定区id查询已经关联的客户
	private String fixedAreaId;
	public void setFixedAreaId(String fixedAreaId) {
		this.fixedAreaId = fixedAreaId;
	}
	
	@Action(value="fixedArea_findAssociationCustomer",results={@Result(name="success",type="json")})
	public String findAssociationCustomer() {
		Collection<? extends Customer> collection = WebClient
				.create(Constants.CRM_MANAGEMENT_URL + "/services/customerService").accept(MediaType.APPLICATION_JSON)
				.path("/findHasAssociationFixedAreaCustomers/" + fixedAreaId).getCollection(Customer.class);
		ServletActionContext.getContext().getValueStack().push(collection);
		return SUCCESS;
	}
}
